package 知识点复习.异步回调.创建子任务;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class CompletableFutureDemo {
    //创建一个无消耗值(无输入值)、无返回值的异步子任务
    public static void runAsyncDemo() throws Exception {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(1000);
                System.out.println("run end...");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        //等待异步任务执行完成，限时等待2秒
        future.get(2, TimeUnit.SECONDS);
    }

    //创建一个无消耗值(无输入值)、有返回值的异步子任务
    public static void supplyAsyncDemo() throws Exception {
        CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
            long start = System.currentTimeMillis();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("run end...");
            return System.currentTimeMillis() - start;
        });
        //等待异步任务执行完成，限时等待2秒
        long time = future.get(2, TimeUnit.SECONDS);
        System.out.println("异步执行耗时(秒)：" + time / 1000);
    }

    public static void main(String[] args) throws Exception {
//        runAsyncDemo();
        supplyAsyncDemo();
    }
}
